import { ref, computed } from 'vue'
import { supabase } from '../../lib/supabase'
import { useUserStore } from '../../store/useUserStore'
import type { 
  Tag, 
  TagCategory, 
  TagStatistics, 
  CreateTagCategoryParams, 
  CreateTagParams, 
  UpdateTagCategoryParams, 
  UpdateTagParams 
} from './types'

export const useTagManagement = () => {
  const userStore = useUserStore()
  const { isAdmin } = userStore
  
  // 状态
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 数据
  const categories = ref<TagCategory[]>([])
  const tags = ref<Record<string, Tag[]>>({})
  const tagStatistics = ref<TagStatistics>({
    total_tags: 0,
    total_categories: 0,
    total_usage: 0,
    active_tags: 0
  })

  // 获取所有标签分类
  const fetchCategories = async () => {
    try {
      loading.value = true
      error.value = null

      const { data, error: fetchError } = await supabase
        .from('tag_categories')
        .select('*')
        .order('sort_order')

      if (fetchError) throw fetchError

      categories.value = data || []
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取标签分类失败'
      console.error('获取标签分类失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取指定分类的标签
  const fetchTagsByCategory = async (categoryName: string) => {
    try {
      loading.value = true
      error.value = null

      console.log(`开始获取${categoryName}分类的标签...`)
      const { data, error: fetchError } = await supabase
        .rpc('get_tags_by_category', { category_name: categoryName })

      if (fetchError) {
        console.error(`获取${categoryName}标签的数据库错误:`, fetchError)
        throw fetchError
      }

      tags.value[categoryName] = data || []
      console.log(`获取${categoryName}标签完成:`, data)
    } catch (err) {
      error.value = err instanceof Error ? err.message : `获取${categoryName}标签失败`
      console.error(`获取${categoryName}标签失败:`, err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取所有标签
  const fetchAllTags = async () => {
    try {
      loading.value = true
      error.value = null

      // 获取所有分类
      await fetchCategories()
      console.log('获取分类完成:', categories.value)

      // 获取每个分类的标签
      const categoryNames = categories.value.map(cat => cat.name)
      console.log('准备获取标签的分类:', categoryNames)
      
      await Promise.all(categoryNames.map(name => fetchTagsByCategory(name)))
      console.log('获取所有标签完成:', tags.value)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取标签失败'
      console.error('获取标签失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取标签统计
  const fetchTagStatistics = async () => {
    try {
      const { data, error: fetchError } = await supabase
        .from('tag_statistics_view')
        .select('*')
        .single()

      if (fetchError) throw fetchError

      if (data) {
        tagStatistics.value = {
          total_tags: data.total_tags ?? 0,
          total_categories: data.total_categories ?? 0,
          total_usage: data.total_usage ?? 0,
          active_tags: data.active_tags ?? 0
        }
      }
    } catch (err) {
      console.error('获取标签统计失败:', err)
    }
  }

  // 创建标签分类
  const createTagCategory = async (params: CreateTagCategoryParams) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以创建标签分类')
      }

      const { data, error: createError } = await supabase
        .from('tag_categories')
        .insert(params)
        .select()
        .single()

      if (createError) throw createError

      // 重新获取分类列表
      await fetchCategories()

      return data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建标签分类失败'
      console.error('创建标签分类失败:', err)
      throw err
    }
  }

  // 更新标签分类
  const updateTagCategory = async (params: UpdateTagCategoryParams) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以更新标签分类')
      }

      const { data, error: updateError } = await supabase
        .from('tag_categories')
        .update(params)
        .eq('id', params.id)
        .select()
        .single()

      if (updateError) throw updateError

      // 重新获取分类列表
      await fetchCategories()

      return data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新标签分类失败'
      console.error('更新标签分类失败:', err)
      throw err
    }
  }

  // 创建标签
  const createTag = async (params: CreateTagParams) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以创建标签')
      }

      const { data, error: createError } = await supabase
        .from('tags')
        .insert(params)
        .select()
        .single()

      if (createError) throw createError

      // 重新获取标签列表
      await fetchAllTags()

      return data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建标签失败'
      console.error('创建标签失败:', err)
      throw err
    }
  }

  // 更新标签
  const updateTag = async (params: UpdateTagParams) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以更新标签')
      }

      const { data, error: updateError } = await supabase
        .from('tags')
        .update(params)
        .eq('id', params.id)
        .select()
        .single()

      if (updateError) throw updateError

      // 重新获取标签列表
      await fetchAllTags()

      return data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新标签失败'
      console.error('更新标签失败:', err)
      throw err
    }
  }

  // 删除标签分类
  const deleteTagCategory = async (categoryId: number) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以删除标签分类')
      }

      // 首先删除该分类下的所有标签
      const { error: deleteTagsError } = await supabase
        .from('tags')
        .delete()
        .eq('category_id', categoryId)

      if (deleteTagsError) throw deleteTagsError

      // 然后删除分类
      const { error: deleteError } = await supabase
        .from('tag_categories')
        .delete()
        .eq('id', categoryId)

      if (deleteError) throw deleteError

      // 重新获取分类列表
      await fetchCategories()

      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除标签分类失败'
      console.error('删除标签分类失败:', err)
      throw err
    }
  }

  // 删除标签
  const deleteTag = async (tagId: number) => {
    try {
      // 检查管理员权限
      const adminStatus = await isAdmin()
      if (!adminStatus) {
        throw new Error('权限不足：只有管理员可以删除标签')
      }

      // 首先删除该标签的所有关联
      const { error: deleteMovieTagsError } = await supabase
        .from('movie_tags')
        .delete()
        .eq('tag_id', tagId)

      if (deleteMovieTagsError) throw deleteMovieTagsError

      // 然后删除标签
      const { error: deleteError } = await supabase
        .from('tags')
        .delete()
        .eq('id', tagId)

      if (deleteError) throw deleteError

      // 重新获取标签列表
      await fetchAllTags()

      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除标签失败'
      console.error('删除标签失败:', err)
      throw err
    }
  }

  // 获取热门标签
  const getPopularTags = async (limit: number = 10) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('get_popular_tags', { p_limit: limit })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('获取热门标签失败:', err)
      return []
    }
  }

  // 搜索标签
  const searchTags = async (searchTerm: string, categoryName?: string, limit: number = 20) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('search_tags', { 
          p_search_term: searchTerm,
          p_category_name: categoryName,
          p_limit: limit
        })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('搜索标签失败:', err)
      return []
    }
  }

  // 为电影推荐标签
  const recommendTagsForMovie = async (movieId: number, limit: number = 10) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('recommend_tags_for_movie', { 
          p_movie_id: movieId,
          p_limit: limit
        })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('获取标签推荐失败:', err)
      return []
    }
  }

  // 获取标签使用趋势
  const getTagUsageTrends = async (days: number = 30) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('get_tag_usage_trends', { p_days: days })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('获取标签使用趋势失败:', err)
      return []
    }
  }

  // 清理未使用的标签
  const cleanupUnusedTags = async (minUsageCount: number = 0, dryRun: boolean = true) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('cleanup_unused_tags', { 
          p_min_usage_count: minUsageCount,
          p_dry_run: dryRun
        })

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('清理未使用标签失败:', err)
      throw err
    }
  }

  // 导出标签数据
  const exportTagsData = async () => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('export_tags_data')

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('导出标签数据失败:', err)
      throw err
    }
  }

  // 计算属性
  const categoryOptions = computed(() => 
    categories.value.map(cat => ({
      value: cat.id,
      label: cat.display_name
    }))
  )

  const activeCategories = computed(() => 
    categories.value.filter(cat => cat.is_active)
  )

  const allTags = computed(() => {
    const result: Tag[] = []
    Object.values(tags.value).forEach(categoryTags => {
      result.push(...categoryTags)
    })
    return result
  })

  const activeTags = computed(() => 
    allTags.value.filter(tag => tag.is_active)
  )

  return {
    // 状态
    loading,
    error,
    
    // 数据
    categories,
    tags,
    tagStatistics,
    
    // 计算属性
    categoryOptions,
    activeCategories,
    allTags,
    activeTags,
    
    // 基础方法
    fetchCategories,
    fetchTagsByCategory,
    fetchAllTags,
    fetchTagStatistics,
    createTagCategory,
    updateTagCategory,
    createTag,
    updateTag,
    deleteTagCategory,
    deleteTag,
    getPopularTags,
    
    // 高级功能
    searchTags,
    recommendTagsForMovie,
    getTagUsageTrends,
    cleanupUnusedTags,
    exportTagsData
  }
}
